<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>叉乘</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css?v=3.3.7}"/>
    <link rel="stylesheet" th:href="@{/ajax/libs/bootstrap-table/bootstrap-table.min.css?v=1.22.6}"/>
    <link rel="stylesheet" th:href="@{/ruoyi/css/ry-ui.css?v=4.7.9}"/>
    <link href="../static/semantic/semantic.min.css" rel="stylesheet" th:href="@{/semantic/semantic.min.css}"/>
    <link href="../static/css/batch.css" rel="stylesheet" th:href="@{/css/batch.css}"/>
    <link th:href="@{/css/font-awesome.min.css}" rel="stylesheet"/>
    <th:block th:include="include :: datetimepicker-css"/>
    <th:block th:include="include :: jasny-bootstrap-css" />
</head>
<body>

<div style="padding: 0 20px 0 20px">
    <div class="row">
        <div class="ui masthead vertical segment">
            <div class="column">
                <div id="toolbar">
                    <input id="importDataI" style="display: none;" type="file"/>
                    <button class="ui basic button" onclick="importData()">
                        <i class="fa fa-upload"></i> 导入模板
                    </button>
                    <a href="/excel/导入模板.xlsx">
                        <button class="ui basic button">
                            <i class="fa fa-download"></i> 下载模板
                        </button>
                    </a>
                    <button class="ui basic button" onclick="deleteLine()">
                        <i class="fa fa-remove"></i> 删除选中行
                    </button>
                    <button class="ui basic button" onclick="resetDuplicateBox()">
                        <input checked id="DuplicateBox" style="height: 11px" type="checkbox">默认选中同名计划、组
                    </button>

                </div>
                <div class="ui segment">
                    <div class="ui  inverted dimmer adTable">
                        <div class="ui text loader">正在加载</div>
                    </div>
                    <table data-resizable="true" id="bootstrap-table"></table>
                </div>
            </div>
        </div>
    </div>

    <div class="row" style="margin-top: -15px">
        <div class="ui masthead vertical segment">
            <div class="column">
                <div class="ui segment">
                    <div class="ui top attached tabular menu tabMenu" style="background-color: #fff">
                        <a class="item active" data-tab="plan">计划</a>
                        <a class="item" data-tab="group">组</a>
                        <a class="item" data-tab="ads">创意</a>
                        <button class="ui blue button" id="submit" onclick="submit()"
                                style="height: 37px;margin: 2px 0 0 5px;">
                            <i class="fa fa-arrow-up"></i> 提交
                        </button>
                    </div>
                    <div class="ui bottom attached tab segment active" data-tab="plan">
                        <form class="ui form" id="plan">
                            <div class="field">
                                <label>推广目标:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" disabled name="adType" tabindex="0" type="radio"
                                                   value="2">
                                            <label>应用推广</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input checked class="hidden" name="adType" tabindex="0" type="radio"
                                                   value="1">
                                            <label>普通网址</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" name="adType" tabindex="0" type="radio" value="8">
                                            <label>快应用/快游戏</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" name="adType" tabindex="0" type="radio" value="11">
                                            <label>小程序</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="field">
                                <label>计划类型:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input checked class="hidden" name="mediaType" tabindex="0" type="radio"
                                                   value="1">
                                            <label>非商店</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" name="mediaType" tabindex="0" type="radio" value="2">
                                            <label>联盟</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="field">
                                <label>广告类型:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input checked class="hidden" name="campaignType" tabindex="0"
                                                   type="radio" value="0">
                                            <label>展示广告</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" disabled name="campaignType" tabindex="0"
                                                   type="radio" value="1">
                                            <label>搜索广告</label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="field">
                                <label>日限额:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input checked class="hidden" data-flag="pass" name="dailyBudgetR1"
                                                   tabindex="0" type="radio" value="0">
                                            <label>不限额</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" data-flag="pass" name="dailyBudgetR1" tabindex="0"
                                                   type="radio" value="1">
                                            <label>自定义</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui input hidden dailyBudget1">
                                            <input data-flag="money" id="dailyBudget1" name="dailyBudget"
                                                   placeholder="请输入金额" type="number" value="-1">
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="field">
                                <label>计划状态（启停，默认关闭）:</label>
                                <div class="field">
                                    <div class="inline field">
                                        <div class="ui slider checkbox">
                                            <input class="hidden" name="planStat" tabindex="0" type="checkbox">
                                        </div>
                                        <label></label>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="ui bottom attached tab segment" data-tab="group">
                        <form class="ui form " id="group">
                            <div class="field">
                                <label>微信一键关注:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="inline field">
                                            <div class="ui toggle checkbox">
                                                <input class="hidden" id="wechatFollow" name="wechatFollow" tabindex="0"
                                                       type="checkbox" value="1">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="field">
                                <label>定向包:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="inline field">
                                            <div class="ui toggle checkbox">
                                                <select class="ui search dropdown" id="audienceInfo"
                                                        name="audienceInfo">
                                                    <option value="">全部不限</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="field ">
                                <label>投放日期:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="inline fields">
                                            <div class="field">
                                                <div class="ui radio checkbox">
                                                    <input checked class="hidden" data-flag="pass" name="dateType"
                                                           tabindex="0" type="radio" value="0">
                                                    <label>长期投放</label>
                                                </div>
                                            </div>
                                            <div class="field">
                                                <div class="ui radio checkbox">
                                                    <input class="hidden" data-flag="pass" name="dateType" tabindex="0"
                                                           type="radio" value="1">
                                                    <label>指定开始和结束日期</label>
                                                </div>
                                            </div>
                                            <div class="field">
                                                <div class="input-group date">
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-calendar"></i></span>
                                                    <input class="form-control" id="startDate" placeholder="yyyy-MM-dd"
                                                           type="text">
                                                </div>
                                            </div>
                                            <div class="field dateD hidden"> 到</div>
                                            <div class="field dateD hidden">
                                                <div class="input-group date">
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-calendar"></i></span>
                                                    <input class="form-control" id="endDate" placeholder="yyyy-MM-dd"
                                                           type="text">
                                                </div>
                                            </div>
                                            <div class="field hidden">
                                                <input id="relStartDate" name="startDate" type="text">
                                                <input id="relEndDate" name="endDate" type="text">
                                            </div>

                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="field">
                                <label>投放时段:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="inline fields">
                                            <div class="field">
                                                <div class="ui radio checkbox">
                                                    <input checked class="hidden" data-flag="pass" name="scheduleTimeRadio"
                                                           tabindex="0" type="radio" value="1">
                                                    <label>不限</label>
                                                </div>
                                            </div>
                                            <div class="field">
                                                <div class="ui radio checkbox">
                                                    <input class="hidden" data-flag="pass" name="scheduleTimeRadio" tabindex="0"
                                                           type="radio" value="2">
                                                    <label>设置</label>
                                                </div>
                                            </div>
                                            <div class="field hidden">
                                                <input class="form-control" id="scheduleTime" name="scheduleTime"
                                                       type="text"
                                                       value="111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="field hidden" id="scheduleTimeD">
                                <table class="scheduleTimeT" id="scheduleTimeT">
                                    <thead>
                                    <tr>
                                        <th class="first-column" rowspan="2"></th>
                                        <th colspan="2">0</th>
                                        <th colspan="2">1</th>
                                        <th colspan="2">2</th>
                                        <th colspan="2">3</th>
                                        <th colspan="2">4</th>
                                        <th colspan="2">5</th>
                                        <th colspan="2">6</th>
                                        <th colspan="2">7</th>
                                        <th colspan="2">8</th>
                                        <th colspan="2">9</th>
                                        <th colspan="2">10</th>
                                        <th colspan="2">11</th>
                                        <th colspan="2">12</th>
                                        <th colspan="2">13</th>
                                        <th colspan="2">14</th>
                                        <th colspan="2">15</th>
                                        <th colspan="2">16</th>
                                        <th colspan="2">17</th>
                                        <th colspan="2">18</th>
                                        <th colspan="2">19</th>
                                        <th colspan="2">20</th>
                                        <th colspan="2">21</th>
                                        <th colspan="2">22</th>
                                        <th colspan="2">23</th>
                                    </tr>

                                    </thead>
                                    <tbody>
                                    <!-- 生成周一到周日的行 -->
                                    <script>
                                        const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                                        days.forEach(day => {
                                            document.write('<tr><td class="first-column">' + day + '</td>');
                                            for (let i = 0; i < 48; i++) {
                                                document.write('<td class="body-column"></td>');
                                            }
                                            document.write('</tr>');
                                        });
                                    </script>
                                    </tbody>
                                </table>
                            </div>
                            <div class="field">
                                <label>日限额:</label>
                                <div class="inline fields">
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input checked class="hidden" data-flag="pass" name="dailyBudgetR2"
                                                   tabindex="0" type="radio" value="0">
                                            <label>不限额</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui radio checkbox">
                                            <input class="hidden" data-flag="pass" name="dailyBudgetR2" tabindex="0"
                                                   type="radio" value="1">
                                            <label>自定义</label>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <div class="ui input hidden dailyBudget2">
                                            <input data-flag="money" id="dailyBudget2" name="dailyBudget"
                                                   placeholder="请输入金额" type="number" value="-1">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="inline fields">
                                <div class="field">
                                    <label>出价方式:</label>
                                    <div class="inline fields">
                                        <div class="field">
                                            <div class="ui radio checkbox">
                                                <input class="hidden" disabled id="chargeType1" name="chargeType"
                                                       tabindex="0" type="radio" value="1">
                                                <label>CPM</label>
                                            </div>
                                        </div>
                                        <div class="field">
                                            <div class="ui radio checkbox">
                                                <input class="hidden" disabled id="chargeType2" name="chargeType"
                                                       tabindex="0" type="radio" value="2">
                                                <label>CPC</label>
                                            </div>
                                        </div>
                                        <div class="field">
                                            <div class="ui radio checkbox">
                                                <input checked class="hidden" id="chargeType3" name="chargeType"
                                                       tabindex="0" type="radio" value="3">
                                                <label>oCpc</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="field ocpxPrice">
                                    <label>优化目标:</label>
                                    <div class="inline fields">
                                        <div class="field">
                                            <div class="ui input dailyBudget">
                                                <select id="ocpxPriceS" name="cvType">
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="field">
                                    <label>出价: <span id="priceRangeTip">元/千次曝光 出价范围为6-999元</span></label>
                                    <div class="inline fields">
                                        <div class="field">
                                            <div class="ui input">
                                                <input data-flag="money" id="spinnerInput" name="price"
                                                       placeholder="请输入金额" type="number" value="6">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="field" id="biddingStrategy" style="display: none;">
                                    <label>出价策略:</label>
                                    <div class="inline fields">
                                        <div class="field">
                                            <div class="ui radio checkbox">
                                                <input checked class="hidden" id="biddingStrategy1" name="biddingStrategy"
                                                       tabindex="0" type="radio" value="0">
                                                <label>稳定拿量</label>
                                            </div>
                                        </div>
                                        <div class="field">
                                            <div class="ui radio checkbox">
                                                <input class="hidden" id="biddingStrategy2" name="biddingStrategy"
                                                       tabindex="0" type="radio" value="1">
                                                <label>优先拿量</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="ui bottom attached tab segment" data-tab="ads">

                        <div class="row" style="background-color:#f5f7ff;margin: 0 4px 10px 4px;">
                            <div class="col-md-12">
                                <div class="col-md-2 adsTitleDiv">
                                    <div class="adsInnerDiv">
                                        <span class="adsCount scNum" id="scNum">0</span>
                                    </div>
                                    <span class="adsLabel">素材</span>
                                </div>

                                <div class="col-md-1 adsTitleDiv">
                                    <h1 class="adsSymbol">X</h1>
                                </div>
                                <div class="col-md-2 adsTitleDiv">
                                    <div class="adsInnerDiv">
                                        <span class="adsCount titNum" id="titNum">0</span>
                                    </div>
                                    <span class="adsLabel">创意文案</span>
                                </div>
                                <div class="col-md-1 adsTitleDiv">
                                    <h1 class="adsSymbol">=</h1>
                                </div>
                                <div class="col-md-2 adsTitleDiv">
                                    <div class="adsInnerDiv">
                                        <span class="adsCount" id="mathNum">0</span>
                                    </div>
                                    <span class="adsLabel">预估创意数量</span>
                                </div>

                                <div class="col-md-2 adsTitleDiv">
                                    <div class="adsInnerDiv">
                                        <span class="adsCount adsNum" id="adsNum">0</span>
                                    </div>
                                    <span class="adsLabel">广告数量</span>
                                </div>

                                <div class="col-md-2 adsTitleDiv">
                                    <div class="adsInnerDiv cursor-pointer" onclick="makeEditable()">
                                        <span class="adsCount" id="adsFNum">0</span>
                                    </div>
                                    <a class="adsLabel" onclick="showAdsModal()">单广告分配创意数量<i
                                            class="cog icon"></i></a>
                                </div>

                            </div>
                        </div>
                        <div class="ui grid">
                            <div class="four wide column" style="padding-right: 7px;">
                                <h4 class="ui top attached block header">创意文案（<span class="titNum">0</span>）</h4>
                                <div class="ui bottom attached segment adsBut">
                                    <div class="column">
                                        <div class="ui input ">
                                            <input id="titleStr" placeholder="多个文案使用空格隔开" type="text"/>
                                        </div>
                                        <a class="ui basic button small " onclick="addTitle()"><i class="plus icon"></i>增加</a>
                                        <a class="ui red basic button small" onclick="removeTitleList()"><i
                                                class="trash icon"></i>清空</a>
                                    </div>
                                    <div id="titleList" style="margin-top: 15px"></div>
                                </div>
                            </div>
                            <div class="twelve wide column" style="padding-left: 7px;">
                                <h4 class="ui top attached block header">创意素材（<span class="scNum">0</span>）</h4>
                                <div class="ui bottom attached segment adsBut">
                                    <form class="ui form" id="ads">
                                        <div class="field">
                                            <label>展现形式:</label>
                                            <div class="inline fields">
                                                <div class="field">
                                                    <div class="ui radio checkbox">
                                                        <input class="hidden" data-flag="pass" name="placeType" tabindex="0"
                                                               type="radio" value="1">
                                                        <label>信息流</label>
                                                    </div>
                                                </div>
                                                <div class="field">
                                                    <div class="ui radio checkbox">
                                                        <input class="hidden" data-flag="pass" disabled name="placeType"
                                                               tabindex="0" type="radio" value="2">
                                                        <label>开屏</label>
                                                    </div>
                                                </div>
                                                <div class="field">
                                                    <div class="ui radio checkbox">
                                                        <input class="hidden" data-flag="pass" disabled name="placeType"
                                                               tabindex="0" type="radio" value="3">
                                                        <label>Banner</label>
                                                    </div>
                                                </div>
                                                <div class="field">
                                                    <div class="ui radio checkbox">
                                                        <input class="hidden" data-flag="pass" disabled name="placeType"
                                                               tabindex="0" type="radio" value="4">
                                                        <label>插屏</label>
                                                    </div>
                                                </div>
                                                <div class="field">
                                                    <div class="ui radio checkbox">
                                                        <input class="hidden" data-flag="pass" disabled name="placeType"
                                                               tabindex="0" type="radio" value="5">
                                                        <label>原生</label>
                                                    </div>
                                                </div>
                                                <div class="field">
                                                    <div class="ui radio checkbox">
                                                        <input class="hidden" data-flag="pass" disabled name="placeType"
                                                               tabindex="0" type="radio" value="9">
                                                        <label>激励视频</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="field">
                                            <label>创意类型:</label>
                                            <div class="inline fields" id="displayModeD">
                                            </div>
                                        </div>
                                        <div class="field">
                                            <label>创意规格:</label>
                                            <div class="inline fields" id="normD">
                                            </div>
                                        </div>
                                        <div class="ui orange button" onclick="addAds()">
                                            <i class="fa fa-plus"></i> 新增创意类型<span id="adsNumType">0</span></div>
                                        <div class="ui red button" onclick="clearAds()">
                                            <i class="fa fa-times"></i> 清空
                                        </div>
                                        <div class="ui clearing divider"></div>
                                        <div class="ui link cards" id="adsCard">
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: jasny-bootstrap-js" />
<th:block th:include="include :: bootstrap-table-resizable-js"/>
<th:block th:include="include :: datetimepicker-js"/>
<script src="../static/semantic/semantic.min.js" th:src="@{/semantic/semantic.min.js}"></script>
<script src="../static/js/batch.js" th:src="@{/js/batch.js}"></script>
<script src="../static/js/dateTimeX.js" th:src="@{/js/dateTimeX.js}"></script>

<script>

</script>

<!-- 文案相关 -->
<script>
    //存放文案
    var titleList = [];
    //增加文案
    function addTitle() {
        var inputStr = $('#titleStr').val();
        if (!inputStr || inputStr.trim() === '') {
            return false;
        }
        var strArray = inputStr.trim().split(/\s+/);
        strArray.forEach(function (str) {
            str = replaceEnglishPunctuation(str);
            var uuid = generateUUID();
            if (str.length >= 6 && str.length <= 26) {
                titleList.push({id: uuid, text: str});
                var messageDiv = `
                        <div class="ui message" id="${uuid}">
                            <i class="close icon" onclick="removeByID('${uuid}')"></i>
                            <div class="header">
                                <p style="font-size: 14px;font-weight: normal;">${str}</p>
                            </div>
                        </div>
                    `;
                $('#titleList').append(messageDiv);
            } else {
                $.modal.msgWarning("文案长度限制6-26个字符，已排除不符合项...");
            }
        });
        // 更新页面上的标题数
        $('.titNum').text(titleList.length);
        restMathNum();
        $('#titleStr').val("");
    }
    /**
     * 将字符串中的英文标点符号替换为对应的中文标点符号
     * @param {string} str - 要处理的字符串
     * @returns {string} 处理后的字符串
     */
    function replaceEnglishPunctuation(str) {
        if (!str || typeof str !== 'string') {
            return str;
        }

        // 英文标点到中文标点的映射表
        const punctuationMap = {
            ',': '，',   // 英文逗号
            // '.': '。',   // 英文句号
            ';': '；',   // 英文分号
            ':': '：',   // 英文冒号
            '?': '？',   // 英文问号
            '!': '！',   // 英文感叹号
            '(': '（',   // 英文左括号
            ')': '）',   // 英文右括号
            '[': '【',   // 英文左方括号
            ']': '】',   // 英文右方括号
            '"': '“',    // 英文双引号
            "'": '‘',    // 英文单引号
            '<': '《',    // 英文左尖括号 (通常用于书名号)
            '>': '》'     // 英文右尖括号 (通常用于书名号)
            // 注意：顿号 (、) 和中文引号（“”, ‘’) 在英文中没有直接对应的单个字符，这里根据常见的替换习惯处理。
            // 英文双引号 " 替换为中文双引号 “”, 但需要注意的是，中文双引号是两个字符。这里的替换是单个字符到单个字符的映射，所以将英文双引号 " 替换为中文左双引号 “ 或 右双引号 ” 可能更准确，但更常见的是直接替换为单个中文双引号字符。为了简洁和兼容性，我这里将英文双引号统一替换为中文左双引号 “。
            // 英文单引号 ' 替换为中文单引号 ‘’, 同上，这里将英文单引号 ' 替换为中文左单引号 ‘。
            // 如果需要更复杂的中文引号替换，例如成对替换，则需要更复杂的逻辑。
        };

        // 创建正则表达式匹配所有英文标点
        // 注意：在正则表达式中，一些特殊字符需要转义，例如 . ? ! ( ) [ ] 等。
        // 为了方便，我们先获取需要转义的键，然后构建正则表达式。
        const escapeRegex = /[.*+?^${}()|[\]\\]/g; // 需要转义的字符
        const escapedKeys = Object.keys(punctuationMap).map(key => key.replace(escapeRegex, '\\$&')); // 转义后的键
        const englishPunctuationRegex = new RegExp(`[${escapedKeys.join('')}]`, 'g');


        // 这里您原代码中有一个 $.modal.msgSuccess("检测到英文标点符号，已自动替换为中文符号"); 的提示，我保留了。
        // 请确保您的环境中包含了 $.modal.msgSuccess 的定义。
        // $.modal.msgSuccess("检测到英文标点符号，已自动替换为中文符号");

        // 替换所有匹配的英文标点
        return str.replace(englishPunctuationRegex, match => punctuationMap[match] || match);

    }
    //文案单个删除
    function removeByID(e) {
        titleList = titleList.filter(function (item) {
            return item.id !== e;
        });
        $('.titNum').text(titleList.length);
        restMathNum();
        $('#' + e).remove();
    }
    //清空文案
    function removeTitleList() {
        // 清空 titleList 数组
        titleList = [];
        $('#titleList').empty(); // 清空页面内容
        // 更新页面上的标题数
        $('.titNum').text(titleList.length);
        // $('.scNum').text(fileCodeS.length);
        restMathNum()
    }

    //重新计算创意数量
    function restMathNum() {
        var scNum = Number($('#scNum').text());
        var titNum = Number($('#titNum').text());
        var adsNum = Number($('#adsNum').text());
        var mathNum = scNum * titNum;
        $('#mathNum').text(mathNum);
        $('#adsFNum').text(adsNum === 0 ? 0 : Math.min(10, Math.floor(mathNum / adsNum)));
    }
</script>
<!--创意相关-->
<script>

    var uploadedFiles = {};
    // 创意数量
    var adsNum = 0;
    // 当前已添加创意类型规格，限制单个类型只能增加一个上传框
    var displayModeAnorm = [];

    function addAds() {
        var displayMode = $('input[name="displayMode"]:checked').attr('label');
        if (displayMode == null) {
            $.modal.msgWarning("请先选择创意类型！");
            return;
        }
        var norm = $('input[name="materialNormId"]:checked').attr('label');
        if (norm == null) {
            $.modal.msgWarning("请先选择创意规格！");
            return;
        }
        var dnType = displayMode + "-" + norm;
        // 检查数组中是否已存在该值
        if (displayModeAnorm.includes(dnType)) {
            $.modal.msgWarning("已存在当前类型上传框！");
            return;
        }
        adsNum += 1;
        var count = $("div[id^='cardD']").length;
        var normId = $('input[name="materialNormId"]:checked').val();
        addCardToAdsCard(adsNum, displayMode, norm, normId);
        displayModeAnorm.push(dnType);
        $('#adsNumType').text(count + 1);
    }

    function clearAds() {
        $('.card').transition('fade', function () {
            $('.card').remove();
        });
        adsNum = 0;
        displayModeAnorm = [];
        $('#adsNumType').text(adsNum);
        restAdsNum();
    }

    function clearAdsBy(index) {
        // fileCodeS = fileCodeS.filter(item => item.index !== index);
        restAdsNum();
    }

    function removeAds(index, type) {
        $(`#cardD${index}`).transition('fade', function () {
            $(`#cardD${index}`).remove();
        });
        displayModeAnorm = displayModeAnorm.filter(item => item !== type);
        var count = $("div[id^='cardD']").length;
        $('#adsNumType').text(count - 1);
        clearAdsBy(index)
    }

    function addCardToAdsCard(index, title, norm, normId) {
        console.log(index);
        console.log(title);
        console.log(norm);
        console.log(normId);


        var newCard = `
    <div class="ui card" id = "cardD${index}" style="width: 100%" >
           <div class="content">
               <div class="header">${index}-${title}-${norm}
               <a onclick="removeAds(${index},'${title}-${norm}')" style="font-size: smaller; font-weight: normal; text-decoration: underline;color: red">删除</a>
               </div>
           </div>
           <div class="content">
               <label class="ui sub header">投放位置</label>
               <select name="virtualPositionId[${index}]" multiple="" class="ui fluid dropdown" data-flag="select">
               </select>
               <div style="margin-top: 25px" id="dynamic-fields-${index}"></div>
           </div>
       </div>
    `;
        // 将新的卡片插入到 #adsCard 中，但不显示
        var $newCard = $(newCard).hide();
        $('#adsCard').append($newCard);

        elementList.forEach(function(item) {
            if (item.valueName === "title") { return; }
            const elementInfo = JSON.parse(item.elementInfo);
            console.log(item);
            console.log(elementInfo);
            if (item.valueName === "avatarCode") {
                const acceptTypes = elementInfo.types.map(type => `.${type}`).join(',');
                $(`#dynamic-fields-${index}`)
                    .append(`<label class="ui sub header">${item.elementName}</label><br>
                <div class="thumbnail" style="max-width: 100px; max-height: 100px; line-height: 10px;margin-bottom: 5px;">
                    <img id="imgView-${index}"src="../../img/addLogo.png"  style="max-height: 90px;" onclick="document.getElementById('avatarCodeFile[${index}]').click()"/>
                </div>
                     <input style="max-width: 500px;" type="file" id="avatarCodeFile[${index}]"
                            accept="${acceptTypes}"
                            data-max-size="${elementInfo.size}"
                            data-width="${elementInfo.width}"
                            data-height="${elementInfo.height}"
                            data-index="${index}"
                            onchange="validateFile(this)"  />
                     <small style="color: #666; display: block; margin-top: 5px;">
                         支持格式: ${elementInfo.types.join(', ')} |
                         最大尺寸: ${elementInfo.size}KB |
                         分辨率必须为: ${elementInfo.width}×${elementInfo.height}像素
                     </small>`);
            }
            if (item.sourceType===2){
                $(`#dynamic-fields-${index}`)
                    .append(`<label class="ui sub header">${item.elementName}</label><br>
                     <input type="text" style="max-width: 500px;"
                        id="textInput-${index}"
                        class="limited-input"
                        maxlength="${elementInfo.maxLength}"
                        placeholder="最多${elementInfo.maxLength}字"
                        oninput="limitInput(this, ${elementInfo.minLength}, ${elementInfo.maxLength})">
                 <small style="color: #666; display: block; margin-top: 5px;">
                     字数限制: ${elementInfo.minLength}-${elementInfo.maxLength}字
                 </small>`);
            }
            if (item.valueName==="imgsCode"){
                const acceptTypes = elementInfo.types.map(type => `.${type}`).join(',');
                $(`#dynamic-fields-${index}`)
                    .append(`<label class="ui sub header">${item.elementName}</label><br>
                    <div id="multi-image-previews-${index}" style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;"></div>
                    <button type="button" class="ui button" onclick="document.getElementById('imgsCodeFile[${index}]').click()">
                        选择文件
                    </button>
                    <button type="button" class="ui red button" onclick="clearAllMultiImages(${index})">
                        清空所有
                    </button>
                    <input style="display: none;" type="file" id="imgsCodeFile[${index}]"
                           accept="${acceptTypes}"
                           data-max-size="${elementInfo.size}"
                           data-width="${elementInfo.width}"
                           data-height="${elementInfo.height}"
                           data-index="${index}"
                           multiple
                           onchange="validateMultiFiles(this, '${index}')" />
                    <small style="color: #666; display: block; margin-top: 5px;">
                        支持格式: ${elementInfo.types.join(', ')} |
                        最大尺寸: ${elementInfo.size}KB (每张) |
                        分辨率必须为: ${elementInfo.width}×${elementInfo.height}像素 (每张)
                    </small>`);
                // Initialize an array to hold files for this specific card
                window.uploadedFiles = window.uploadedFiles || {};
                window.uploadedFiles[index] = [];
            }
        });

        $('.ui.dropdown').dropdown();
        $('.tabMenu').sticky() ;
        // 使用过渡动画显示新卡片
        $newCard.transition('scale');
        getvirtualPositionList(index);

    }

    function resetNorm(index, data) {
        var $select = $(`select[name="virtualPositionId[${index}]"]`); // 根据 name 属性获取 select 元素
        $select.empty();
        data.forEach(function (item) {
            var option = $('<option>', {
                value: item.virtualPositionUuid,    // 设置 value
                text: item.virtualPositionName,    // 设置显示值
                selected: true                     // 默认选中
            });
            $select.append(option);                // 添加到 select 中
        });
    }

    // 获取 投放位置
    function getvirtualPositionList(index) {
        var e = {};
        e.normId = $('input[name="materialNormId"]:checked').val();
        e.mediaType = $('#plan input[name="mediaType"]:checked').val();
        e.adType = $('#plan input[name="adType"]:checked').val();
        e.displayType = $('input[name="placeType"]:checked').val();
        var body = {};
        body.jsonStr = JSON.stringify(e);
        body.uuid = checkList[0].uuid;
        body.token = checkList[0].mainName;

        $.ajax({
            url: "/vivo/api/virtualPositionList",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(body),
            success: function (response) {
                if (JSON.parse(response).code === 0) {
                    resetNorm(index, JSON.parse(response).data)
                } else {
                    $.modal.msgWarning('请求投放位置失败，请联系系统管理员')
                }
            },
            error: function (xhr, status, error) {
                $.modal.msgWarning('服务器内部错误，请联系系统管理员');
            }
        });

    }

    function addTooltipText(name, minLength, maxLength, required, label) {
        // 根据 name 查找对应的 label 元素
        var $label = $(`#${label}`);
        // 设置字符数限制
        var $inputField = $('input[name="' + name + '"]');
        if (minLength !== undefined) {
            $inputField.attr('minlength', minLength);  // 设置最小字符数
        }
        if (maxLength !== undefined) {
            $inputField.attr('maxlength', maxLength);  // 设置最大字符数
        }
        // 设置是否必填
        if (required) {
            $inputField.prop('required', true);  // 设置为必填
        } else {
            $inputField.prop('required', false);  // 取消必填
        }
        // 构造提示语
        var tooltipMessage = `请输入 ${minLength} 至 ${maxLength} 个字符`;
        // 在 label 后面添加提示语
        $label.append(`<span class="tooltip-message">${tooltipMessage}</span>`);

        // 可以添加一些样式来美化提示语
        $('.tooltip-message').css({
            'font-size': '12px',
            'color': '#999',
            'margin-left': '10px'
        });
    }

    function addTooltipImgVideo(label, width, height, size, types) {
        // 根据 name 查找对应的 label 元素
        var $label = $(`#${label}`);
        // 构造提示语
        var tooltipMessage = `大小：${size} KB，尺寸：${width}*${height}，类型：${types}`;

        // 在 label 后面添加提示语
        $label.append(`<span class="tooltip-message">${tooltipMessage}</span>`);
        // 可以添加一些样式来美化提示语
        $('.tooltip-message').css({
            'font-size': '12px',
            'color': '#999',
            'margin-left': '10px'
        });
    }

    //上传图片
    function uploadImg(input, element, e) {
        var $img = $(e);
        // 创建临时的文件输入框
        var $fileInput = $('<input type="file" style="display:none;" accept="image/*" />');

        // 文件类型和尺寸的限制从element获取
        var validTypes = element.types; // 允许的文件类型（如 jpg, jpeg, png）
        var maxSize = element.size * 1024; // 转换为字节
        var minWidth = element.width;
        var minHeight = element.height;

        // 将临时的文件输入框添加到页面
        $('body').append($fileInput);

        // 绑定文件选择事件
        $fileInput.on('change', function (event) {
            var file = event.target.files[0];

            if (!file) {
                console.log("没有选择文件");
                return;
            }

            // 检查文件类型
            var fileType = file.type.split('/')[1]; // 获取文件类型（jpg, png, jpeg）
            if (validTypes.indexOf(fileType) === -1) {
                $.modal.alert('文件类型不支持，支持的类型为: ' + validTypes.join(', '));
                $fileInput.remove(); // 删除临时上传控件
                return;
            }

            // 检查文件大小
            if (file.size > maxSize) {
                $.modal.alert('文件大小超出限制，最大支持 ' + element.size + 'KB');
                $fileInput.remove();
                return;
            }

            // 检查图片尺寸
            var reader = new FileReader();
            reader.onload = function (e) {
                var img = new Image();
                img.onload = function () {
                    if (img.width !== minWidth || img.height !== minHeight) {
                        $.modal.alert('图片尺寸不符合要求，必须为 ' + minWidth + 'x' + minHeight + ' px');
                        $fileInput.remove();
                        return;
                    }

                    // 文件和尺寸验证通过后，调用接口上传文件
                    var formData = new FormData();
                    formData.append('file', file);

                    $.ajax({
                        url: '/oss/upload', // 替换为你的上传接口URL
                        type: 'POST',
                        data: formData,
                        processData: false, // 防止jQuery处理data
                        contentType: false, // 防止jQuery设置content-type
                        success: function (response) {
                            console.log('文件上传成功:', response);
                            // 打印返回的结果（接口返回的数据）
                            if (response.code === 0) {
                                $(`input[name="${input}"]`).val(response.data.fileCode);
                                // $img.attr("src", response.data.fileFullPath);
                                $img.find('img').attr('src', response.data.fileFullPath);

                                // if (input.includes("avatarCode")) {
                                //     // 设置所有 name 为 avatarCode[1], avatarCode[2], avatarCode[3], ... 的输入框值
                                //     $('input[name^="avatarCode"]').each(function() {
                                //         $(this).val(response.data.fileCode);
                                //     });
                                //     // 设置所有 id 为 avatarCode-开头的 img 或其他元素的 src
                                //     $('[id^="avatarCode-"]').each(function() {
                                //         $(this).attr("src", response.data.fileFullPath);
                                //     });
                                // }
                            } else {
                                $.modal.msgWarning(response.msg)
                            }
                        },
                        error: function (error) {
                            $.modal.msgWarning('上传失败:', error);
                        },
                        complete: function () {
                            $fileInput.remove(); // 删除临时上传控件
                        }
                    });
                };
                img.src = e.target.result;
            };
            reader.readAsDataURL(file); // 读取文件
        });

        // 模拟点击文件输入框，打开文件选择框
        $fileInput.click();
    }

    // 视频上传函数
    function uploadVideo(inputName, elementInfo, e, index) {
        console.log(e);
        var a = inputName;
        var b = elementInfo;
        var c = e;
        var d = index;
        var $videoDiv = $(`#${e}`);

        // 创建临时文件选择框
        var tempInput = $('<input type="file" accept="video/*">');
        // 触发文件选择
        tempInput.click();

        // 当文件选择完成后
        tempInput.on('change', function (e) {
            var file = e.target.files[0];
            if (!file) {
                return;
            }
            // 获取文件的类型、大小、宽高
            var fileType = file.type;
            var fileSize = file.size / 1024;  // 转换为KB
            var videoElement = document.createElement('video');
            // 检查文件格式和大小
            if (!elementInfo.types.includes(fileType.split('/')[1])) {
                $.modal.alert('文件类型不符合要求');
                return;
            }
            if (fileSize > elementInfo.size) {
                $.modal.alert(`文件大小不能超过 ${elementInfo.size} KB`);
                return;
            }
            // 加载视频文件获取宽高
            var videoURL = URL.createObjectURL(file);
            videoElement.src = videoURL;
            videoElement.onloadedmetadata = function () {
                // 检查视频宽高
                if (videoElement.videoWidth !== elementInfo.width || videoElement.videoHeight !== elementInfo.height) {
                    $.modal.alert(`视频尺寸必须为 ${elementInfo.width}x${elementInfo.height} px`);
                    return;
                }

                // 创建并显示进度条
                var $progressContainer = $('<div class="progress-container" style="width: 100%; height: 30px; background-color: #f3f3f3; border-radius: 5px; margin-top: 10px;"></div>');
                var $progressBar = $('<div class="progress-bar" style="height: 100%; background-color: #4caf50; width: 0%; border-radius: 5px;"></div>');
                $progressContainer.append($progressBar);
                $videoDiv.append($progressContainer);

                // 使用 FormData 进行上传
                var formData = new FormData();
                formData.append('file', file);

                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/oss/upload', true);

                // 监听进度事件
                xhr.upload.addEventListener('progress', function (e) {
                    if (e.lengthComputable) {
                        var percent = (e.loaded / e.total) * 100;
                        $progressBar.css('width', percent + '%');
                    }
                });

                // 上传成功后的回调
                xhr.onload = function () {
                    if (xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText); // 假设返回的是 JSON 格式数据
                        console.log('文件上传成功:', response);
                        if (response.code === 0) {
                            // 文件上传成功后移除进度条
                            $progressContainer.remove();

                            $(`input[name="${inputName}"]`).val(response.data.fileCode);
                            $videoDiv.find('img').remove();
                            $videoDiv.find('video').remove();
                            $videoDiv.find('a').remove();

                            // 创建视频预览框
                            var videoPreview = `
                            <video width="auto" height="100%" crossorigin="anonymous" controls id="video-${index}">
                                <source src="${response.data.fileFullPath}" type="video/mp4">
                                Your browser does not support the video tag.
                            </video>
                        `;
                            $videoDiv.append(videoPreview);
                            $videoDiv.css({
                                'width': '700',   // 设置宽度自动适配
                                'height': '200'   // 高度根据视频自动调整
                            });

                            // 创建重新上传按钮
                            var $reUploadButton = $('<a class="ui button">重新上传</a>');
                            $videoDiv.append($reUploadButton);
                            // 重新上传按钮点击事件
                            $reUploadButton.on('click', function () {
                                uploadVideo(a, b, c, d);
                            });
                            // 创建抽帧按钮
                            var $frameButton = $('<a class="ui button">抽帧上传预览图</a>');
                            $videoDiv.append($frameButton);
                            // 抽帧按钮点击事件
                            $frameButton.on('click', function () {
                                extractFrameAndUpload(index);
                            });
                        } else {
                            $.modal.msgWarning(response.msg);
                        }
                    } else {
                        $.modal.alert('上传失败，请重试');
                    }
                };

                // 上传失败的回调
                xhr.onerror = function () {
                    $.modal.alert('上传失败，请重试');
                };

                // 发送请求
                xhr.send(formData);
            };
        });
    }

    var isExtractingThumbnail = false; // 标志位，判断是否正在截取封面图
    var isSeeking = false;  // 标志位，判断是否是用户拖动进度条
    // 抽帧并上传
    function extractFrameAndUpload(e) {
        var $video = e;
        var outerDivId = $($video).closest('div').parent().attr('id');
        const video = $video.get(0);
        if (video.poster) {
            return;
        }
        // 创建一个与视频尺寸相同的 Canvas
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        // 将当前帧绘制到 Canvas
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        // 定义压缩参数
        let quality = 0.9; // 初始质量
        let maxSize = 100 * 1024; // 最大大小 (100KB)
        let compressedDataUrl;
        let mimeType = 'image/jpeg'; // 默认压缩为JPEG
        // 尝试压缩图片
        do {
            compressedDataUrl = canvas.toDataURL("image/jpeg", quality);
            quality -= 0.1; // 每次减少质量
        } while (compressedDataUrl.length > maxSize && quality > 0);
        const fileExtension = mimeType === 'image/jpeg' ? '.jpg' : '.png'; // 判断扩展名
        const blob = dataURLtoBlob(compressedDataUrl, mimeType);
        // 调用上传方法
        uploadImg1(blob, fileExtension, outerDivId);
        // 清理资源
        canvas.remove();
    }

    //抽帧并下载
    function extractFrameAndDownload(e) {
        var $video = e;
        const video = $video.get(0);

        // 创建一个与视频尺寸相同的 Canvas
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 将当前帧绘制到 Canvas
        context.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 定义压缩参数
        let quality = 0.9; // 初始质量
        let maxSize = 100 * 1024; // 最大大小 (100KB)
        let compressedDataUrl;
        let mimeType = 'image/jpeg'; // 默认压缩为JPEG

        // 尝试压缩图片
        do {
            compressedDataUrl = canvas.toDataURL("image/jpeg", quality);
            quality -= 0.1; // 每次减少质量
        } while (compressedDataUrl.length > maxSize && quality > 0);

        // 将 Data URL 转换为 Blob
        const blob = dataURLtoBlob(compressedDataUrl, mimeType);

        // 创建一个下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `frame_${Date.now()}.jpg`; // 设置下载文件名
        document.body.appendChild(a);
        a.click(); // 触发下载

        // 清理资源
        URL.revokeObjectURL(url);
        document.body.removeChild(a);
        canvas.remove();
    }

    // 将 Base64 转换为 Blob
    function dataURLtoBlob(dataurl, mimeType) {
        const arr = dataurl.split(',');
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mimeType});
    }

    // 抽帧按钮上传预览图
    function uploadImg1(file, fileExtension, outerDivId) {
        var formData = new FormData();
        const fileName = `captureFrame${fileExtension}`;
        formData.append('file', file, fileName);
        $.ajax({
            url: '/oss/upload', // 替换为你的上传接口URL
            type: 'POST',
            data: formData,
            processData: false, // 防止jQuery处理data
            contentType: false, // 防止jQuery设置content-type
            success: function (response) {
                // 打印返回的结果（接口返回的数据）
                if (response.code === 0) {
                    $.modal.msgSuccess(response.msg);
                    console.log(response.data);
                    fileCodeS.forEach(item => {
                        if (item.videoId.includes(outerDivId)) {
                            item.previewCode = response.data.fileCode;  // 添加 imgCode 属性 预览
                            var escapedOuterDivId = $.escapeSelector(outerDivId);
                            var videoElement = $('#' + escapedOuterDivId).find('video').get(0);
                            setVideoPoster(videoElement, response.data.fileFullPath)
                        }
                    });

                    $('div').filter(function () {
                        return $(this).attr('id') === outerDivId;
                    }).css('box-shadow', '0 4px 8px rgba(0, 255, 0, 0.7)');
                } else {
                    $.modal.msgWarning(response.msg);
                }
            },
            error: function (error) {
                $.modal.msgWarning('上传失败:', error);
            },
            complete: function () {
            }
        });
    }

    function syncProductNames() {
        // 监听所有 productName[xx] 输入框的变化
        $('input[name^="productName"]').on('input', function () {
            // 获取当前输入框的值
            var value = $(this).val();

            // 同步所有 productName[xx] 输入框的值
            $('input[name^="productName"]').val(value);
        });
    }

    function transformData(data) {
        var creativeList = [];
        var keys = Object.keys(data);
        var groupedData = {};

        // 按照索引分组数据
        keys.forEach(function (key) {
            var keyParts = key.split('[');
            console.log(keyParts);

            var mainKey = keyParts[0];
            var index = keyParts[1].replace(']', '');
            if (!groupedData[index]) {
                groupedData[index] = {};
            }
            groupedData[index][mainKey] = data[key];
        });

        // 生成 creativeList
        for (var index in groupedData) {
            var item = groupedData[index];
            var creativeItem = {};

            // 动态构建 creativeItem
            Object.keys(item).forEach(function (field) {
                if (item[field] !== undefined && item[field] !== null) {
                    creativeItem[field] = item[field];
                }
            });

            // 将每个索引下的创意项添加到 creativeList 中
            creativeList.push(creativeItem);
        }

        return {
            "creativeList": creativeList
        };
    }

    function restVideoJS(index, elementList, title, normId) {
        console.log(elementList);
        console.log(title);
        console.log(normId);

        if (title.includes("视频")) {

        } else {

        }

    }

    function videoMenu() {
        // 右键点击 video 元素
        $('video').on('contextmenu', function (e) {
            e.preventDefault(); // 阻止默认的右键菜单

            var videoElement = $(this);  // 当前被右键点击的视频元素
            var menu = $('.custom-menu'); // 使用Semantic UI的Dropdown菜单

            // 设置菜单显示位置
            var posX = e.pageX;
            var posY = e.pageY;

            menu.css({
                top: posY + 'px',
                left: posX + 'px',
                display: 'block'
            });

            // 显示自定义菜单
            menu.dropdown('show'); // 显示Semantic UI的dropdown菜单

            // 确保每次右键菜单弹出时，移除之前绑定的事件，防止事件重复绑定
            menu.find('.capture-thumbnail').off('click').on('click', function () {
                console.log('截取封面功能');
                extractFrameAndUpload(videoElement);
            });
            menu.find('.one-click-capture').off('click').on('click', function () {
                console.log('一键截取功能');
                $('.kv-preview-data.file-preview-video').each(function () {
                    extractFrameAndUpload($(this));
                });
            });
            menu.find('.one-click-captureDow').off('click').on('click', function () {
                extractFrameAndDownload(videoElement);
            });
            menu.find('.upload-thumbnail').off('click').on('click', function () {
                console.log('自定义上传封面功能');
                var input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';  // 限制为图片文件
                input.addEventListener('change', function (event) {
                    var file = event.target.files[0];
                    if (!file) return;
                    var maxSize = 100 * 1024;  // 100KB
                    if (file.size > maxSize) {
                        $.modal.msgWarning('文件大小超过 100KB！');
                        return;
                    }
                    var fileExtension = file.name.split('.').pop();  // 获取文件扩展名
                    var outerDivId = $(videoElement).closest('div').parent().attr('id');
                    uploadImg1(file, '.' + fileExtension, outerDivId);
                });
                input.click();
            });
        });

        // 点击页面任何地方隐藏右键菜单
        $(document).on('click', function () {
            $('.custom-menu').hide();
        });

        // 阻止右键菜单被隐藏
        $('.custom-menu').on('click', function (e) {
            e.stopPropagation();
        });
    }

    function restAdsNum() {
        $('.scNum').text(fileCodeS.length);
        restMathNum()
    }

    function makeEditable() {
        // 获取当前文本内容
        let currentValue = $('#adsFNum').text();

        // 创建一个输入框，限制宽度为 40px，最大值为 10
        let input = $('<input type="number" class="input-number" style="width: 40px;" min="1" max="10">').val(currentValue);

        // 把原始内容替换成输入框
        $('#adsFNum').html(input);

        // 聚焦输入框
        input.focus();

        // 处理输入框失去焦点或按下回车
        input.on('blur keypress', function (event) {
            if (event.type === 'blur' || event.key === 'Enter') {
                // 获取输入值，确保不超过10
                let newValue = parseInt(input.val().trim(), 10);
                if (newValue === "" || newValue > 10 || isNaN(newValue)) {
                    newValue = currentValue; // 恢复原值
                }
                // 替换为文本显示
                $('#adsFNum').text(newValue);
            }
        });
    }

    function restMathNum() {
        var scNum = Number($('#scNum').text());
        var titNum = Number($('#titNum').text());
        var adsNum = Number($('#adsNum').text());
        var mathNum = scNum * titNum;
        $('#mathNum').text(mathNum);
        $('#adsFNum').text(adsNum === 0 ? 0 : Math.min(10, Math.floor(mathNum / adsNum)));
    }

    function setVideoPoster(videoElement, newPosterUrl) {
        if (!videoElement) {
            console.error("Video element is not provided");
            return;
        }
        videoElement.pause();  // 暂停视频
        console.log(newPosterUrl);
        videoElement.poster = newPosterUrl;
        videoElement.load();

    }

    function shuffleArray(array) {
        // 深拷贝数组，避免修改原数组
        const newArray = JSON.parse(JSON.stringify(array));

        for (let i = newArray.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
        }

        // 尽量避免 materialNormId 字段值连续相同
        for (let i = 0; i < newArray.length - 1; i++) {
            if (newArray[i].materialNormId === newArray[i + 1].materialNormId) {
                let j = i + 2;
                while (j < newArray.length && newArray[i].materialNormId === newArray[j].materialNormId) {
                    j++;
                }
                if (j < newArray.length) {
                    [newArray[i + 1], newArray[j]] = [newArray[j], newArray[i + 1]];
                } else {
                    // 如果找不到不同的 materialNormId，则回退到上一个元素进行交换
                    j = i - 1;
                    if (j >= 0) {
                        let k = j - 1;
                        while (k >= 0 && newArray[i + 1].materialNormId === newArray[k].materialNormId) {
                            k--;
                        }
                        if (k >= 0) {
                            [newArray[i + 1], newArray[k]] = [newArray[k], newArray[i + 1]];
                        }
                    }
                    // 在最后找不到合适的位置交换，则维持原样
                }
            }
        }
        return newArray;
    }

    function triggerClicksOnCities(element, input) {
        // 分割输入的字符串
        const arr = input.split(',');
        const city1 = arr[0].trim();
        const city2 = arr[1].trim();

        // 获取符合条件的 span 元素
        function getElementsByText(text) {
            return Array.from(document.querySelectorAll('.ep-cascader-node__label'))
                .filter(span => span.textContent.trim() === text);
        }

        // 执行点击操作
        function triggerSpanClicks(firstText, secondText) {
            // 获取并点击符合第一个字符串条件的第一个 span 元素
            const firstSpans = getElementsByText(firstText);
            if (firstSpans.length > 0) {
                firstSpans[0].click();
                console.log(`触发内容为 "${firstText}" 的第一个 span 点击`);
            }
            // 等待页面更新（假设需要等待一些时间）
            setTimeout(() => {
                // 获取并点击符合第二个字符串条件的最后一个 span 元素
                const secondSpans = getElementsByText(secondText);
                if (secondSpans.length > 0) {
                    const lastSecondSpan = secondSpans[secondSpans.length - 1];
                    lastSecondSpan.click();
                } else {
                    console.log(`未找到内容为 "${secondText}" 的 span`);
                }
            }, 500); // 根据实际情况调整等待时间
        }

        // 调用点击函数，传入 city1 和 city2
        triggerSpanClicks(city1, city2);
    }


</script>
</body>
</html>